package com.yiren.dbaa.net;

import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;

public class OKHttpClient {

    static OkHttpClient mOkHttpClient;
    public final static int READ_TIMEOUT = 30;
    public final static int WRITE_TIMEOUT = 15;
    public final static int CONNECT_TIMEOUT = 10;

    public static OkHttpClient getOKHttpClient() {
        return mOkHttpClient;
    }

    static {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);

        okhttp3.OkHttpClient.Builder ClientBuilder = new okhttp3.OkHttpClient.Builder();
        ClientBuilder.addInterceptor(logging)
                .addInterceptor(new RetryIntercepter(1)) //重试
                .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)      //读取超时
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)    //写入超时
                .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//连接超时
//                .sslSocketFactory(createSSLSocketFactory())  //支持HTTPS请求，跳过证书验证
//                .hostnameVerifier(new HostnameVerifier() {
//                    @Override
//                    public boolean verify(String hostname, SSLSession session) {
//                        return true;
//                    }
//                })
        ;
        mOkHttpClient = ClientBuilder.build();
    }

    /**
     * 生成安全套接字工厂，用于https请求的证书跳过
     *
     * @return
     */
    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory ssfFactory = null;
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, new TrustManager[]{new TrustAllCerts()}, new SecureRandom());
            ssfFactory = sc.getSocketFactory();
        } catch (Exception e) {
        }
        return ssfFactory;
    }

    /**
     * 用于信任所有证书
     */
    static class TrustAllCerts implements X509TrustManager {
        @Override
        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }

}
